package com.example.petstore.controller;

import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.Item;
import com.example.petstore.domain.Product;
import com.example.petstore.service.ItemService;
import com.example.petstore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private ItemService itemService;
    @RequestMapping("/productForm")
    public String productForm(String productId, Model model){
        List<Item> itemList = itemService.getItemListByProductId(productId);
        model.addAttribute("itemList", itemList);
        Product product = productService.
                getProductByProductId(productId);
        model.addAttribute("product", product);
        return "catalog/product";
    }
    @GetMapping("/getProductListByCategory")
    @ResponseBody
    public CommonResponse getProductListByCategory(String category){
        return productService.getProductListByCategory(category);
    }

//    @GetMapping("/getProductListByKey")
//    @ResponseBody
//    public CommonResponse getProductListByKey(String keyWord){
//        return productService.getProductListByKey(keyWord);
//    }

    @GetMapping("/getProductListByKey")
    public String getProductListByKey(String keyword, ModelMap model){
        List<Product> productList = (List<Product>)productService.getProductListByKey(keyword).getData();
        System.out.println(productList);
        if(productList.isEmpty()){
            model.addAttribute("productList", null);
        }else{
            model.addAttribute("productList", productList);
        }
        return "catalog/search";
    }

    /*js获取productList*/
    @GetMapping("/getProductListByKeyForJS")
    @ResponseBody
    public CommonResponse getProductListByKeyForJS(String keyword){
        System.out.println(keyword);
        if(keyword == null || keyword == "")
            return productService.getProductList();
        return productService.getProductListByKey(keyword);
    }
}
